import json
import requests
from bs4 import BeautifulSoup
import re

def get_bchScan_data(tx_hash):
    # 交易网站的网址
    url=f'https://bchblockexplorer.com/tx/{tx_hash}'

    headers = {
            'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0'
        }
    response = requests.get(url=url,headers=headers)

    if response.status_code == 200:
        data_html = response.text

        # 使用BeautifulSoup中的css选择器来提取数据
        soup = BeautifulSoup(data_html, 'html.parser')
        data = soup.find(name='script', attrs={'type': "text/javascript"}).get_text()
        data = re.findall(r"txSpecific = (.*?);function",data)[0]

        # 将json格式的数据转为python格式的数据
        dict_data = json.loads(data)

        print("BCH链数据爬取完成！")
        # json_data = json.dumps(dict_data, indent=4)
        # with open('../data/bchdata.json', 'w', encoding='utf-8') as f:
        #     f.write(json_data)
        return dict_data
    else:
        print(f"Error: {response.status_code}, {response.text}")
# get_bchScan_data("941C462EBEF76B051150A6EC10AC6E02E49828C46265B8103E95D493B0641991")
